package com.duke.shaking;

import java.util.HashMap;
import java.util.Map;

import com.duke.shaking.R;
import com.duke.shaking.interaction.ChatFriendsActivity;
import com.duke.shaking.interaction.ShakeActivity;
import com.duke.shaking.more.MoreActivity;
import com.duke.shaking.net.MessageFetcher;
import com.duke.shaking.net.MessageFetcher.MessageFetchListener;
import com.duke.shaking.profile.MyselfActivity;
import com.duke.shaking.services.PopupUpdateAlertService;
import com.duke.shaking.storage.DataManager;

import android.app.AlertDialog;
import android.app.TabActivity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.Window;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;

public class ShakeTabActivity extends TabActivity implements MessageFetchListener {
	public static final String TAG_SHAKE = "shake";
	public static final String TAG_MSG = "msg";
	public static final String TAG_MYSELF = "myself";
	public static final String TAG_MORE = "more";

	public static final long TITLE_BTN_EXIST = TitleActivity.TITLE_BTN_EXIST;
	public static final long TITLE_BTN_BACK =  TitleActivity.TITLE_BTN_BACK;
	public Button btnLeft;
	public Button btnRight;
	public TextView txtTitle;
	public TextView txtUnreadMsgFlag;
	private Map<String, Integer> mapTagBtn;
	
	protected boolean leftBtnIsBack;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		//getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, 0);
		setContentView(R.layout.activity_shake_tab);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, 
        		R.layout.title);
		txtUnreadMsgFlag = (TextView)findViewById(R.id.flag_tab_unread_msg);
		if (txtUnreadMsgFlag != null) {
			txtUnreadMsgFlag.setVisibility(View.GONE);
		}
		
		mapTagBtn = new HashMap<String, Integer>();
		initTab();
		ShakeTabEvent e = (ShakeTabEvent)this.getCurrentActivity();
		if (e != null) {
			e.onActive(this);
		}
		checkUpdateAndAlert();
		checkUserCompletedAlert();
	}
	
	private void checkUserCompletedAlert() {
		ShakeApplication app = ShakeApplication.getShared();
		if (app.userCompleteChecked) {
			return;
		}
		app.userCompleteChecked = true;
		Intent intent = new Intent(this, PopupUpdateAlertService.class);
		intent.putExtra("user", BaseActivity.me);
		startService(intent);
	}
	
	private void checkUpdateAndAlert() {
		ShakeApplication app = ShakeApplication.getShared(); 
		if (!app.checkUpdate) {
			return;
		}
		PackageManager packageManager = getPackageManager();
		
		PackageInfo packInfo;
		try {
			packInfo = packageManager.getPackageInfo(getPackageName(),0);
			int currVersionCode = packInfo.versionCode;
			int lastVersionCode = app.lastVersionCode;
			if (currVersionCode < lastVersionCode) {
				//String currVersionName = packInfo.versionName;
				String lastVersionName = app.lastVersionName;
				final String updateUrl = app.updateUrl;
				if (updateUrl != null && !updateUrl.equals("")) {
					Builder builder = new Builder(this);
					String msg = String.format(getString(R.string.alert_update_app), lastVersionName);
					
					builder.setMessage(msg);
					builder.setPositiveButton(R.string.alert_update_app_btn_yes, new OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							Uri uri = Uri.parse(updateUrl);
							Intent i = new Intent();
							i.setAction(Intent.ACTION_VIEW);
							i.setData(uri);
							startActivity(i);
							dialog.dismiss();
						}
					});
					builder.setNegativeButton(R.string.alert_update_app_btn_no, new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
					
					AlertDialog alert = builder.create();
					alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
					alert.show();
				}
			}
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		app.checkUpdate = false;
	}
	
	private void initTab() {
		addTab(TAG_SHAKE, ShakeActivity.class, R.id.rb_tab_shake);
		addTab(TAG_MSG, ChatFriendsActivity.class, R.id.rb_tab_msg);
		addTab(TAG_MYSELF, MyselfActivity.class, R.id.rb_tab_myself);
		addTab(TAG_MORE, MoreActivity.class, R.id.rb_tab_more);
	}
	
	private void addTab(String tag, Class<?> cls, int tabBtnId) {
		mapTagBtn.put(tag, tabBtnId);
		getTabHost().addTab(getTabHost().newTabSpec(tag).setIndicator(tag).setContent(
				new Intent(this, cls)));
		bindChangedEvent(tabBtnId, tag);
		 
	}
	
	private void uncheckTab(int btnId) {
		RadioButton btn = (RadioButton) findViewById(btnId);
		if (btn != null) {
			if (btn.isChecked()) {
				btn.setChecked(false);
			}
		}
	}
	
	private void bindChangedEvent(final int btnId, final String tag) {
		final RadioButton btn = (RadioButton) findViewById(btnId);
		if (btn != null) {
			btn.setOnClickListener(new View.OnClickListener() {
				public void onClick(View arg0) {
					switchTab(btnId, tag);
				}
			});
		}
	}

	private void switchTab(int btnId, String tag) {
		if (tag.equals(getTabHost().getCurrentTabTag())) {
			return;
		}
		getTabHost().setCurrentTabByTag(tag);
		if (btnId != R.id.rb_tab_shake) {
			uncheckTab(R.id.rb_tab_shake);
		}
		if (btnId != R.id.rb_tab_msg) {
			uncheckTab(R.id.rb_tab_msg);
		}
		if (btnId != R.id.rb_tab_myself) {
			uncheckTab(R.id.rb_tab_myself);
		}
		if (btnId != R.id.rb_tab_more) {
			uncheckTab(R.id.rb_tab_more);
		}
		
		onTabChanged(tag);
	}
	
	public void selectTabByTag(String tag) {
		Integer btnId = mapTagBtn.get(tag);
		if (btnId != null) {
			switchTab(btnId, tag);
		}
	}
	
	private void onTabChanged(String tabTag) {
		ShakeTabEvent e = (ShakeTabEvent)this.getCurrentActivity();
		if (e != null) {
			e.onActive(this);
		}
	}
	
	public void initTitle(long leftBtnStyle, int leftBtnText,
			long rightBtnStyle, int rightBtnText,
			int titleText) {
		btnLeft = (Button)findViewById(R.id.btn_left);
		btnRight = (Button)findViewById(R.id.btn_right);
		txtTitle = (TextView)findViewById(R.id.txt_title);
		if ((leftBtnStyle & TITLE_BTN_EXIST) != 0) {
			if (btnLeft != null) {
				btnLeft.setVisibility(View.VISIBLE);
				btnLeft.setText(leftBtnText);
				if ((leftBtnStyle & TITLE_BTN_BACK) != 0) {
					btnLeft.setBackgroundResource(R.drawable.back);
					leftBtnIsBack = true;
				}
				else {
					btnLeft.setBackgroundResource(R.drawable.go);
				}
			}
		}
		else {
			if (btnLeft != null) {
				btnLeft.setVisibility(View.INVISIBLE);
			}
		}
		if ((rightBtnStyle & TITLE_BTN_EXIST) != 0) {
			if (btnRight != null) {
				btnRight.setVisibility(View.VISIBLE);
				btnRight.setText(rightBtnText);
				btnRight.setBackgroundResource(R.drawable.go);
			}
		}
		else {
			if (btnRight != null) {
				btnRight.setVisibility(View.INVISIBLE);
			}
		}
		if (titleText > 0) {
			txtTitle.setText(titleText);
		}
	}
	
	public void onLeftBtn(View v) {
		ShakeTabEvent e = (ShakeTabEvent)this.getCurrentActivity();
		if (leftBtnIsBack) {
			if (e != null) {
				e.onBackBtn();
			}
			finish();
		}
		else {
			if (e != null) {
				e.onLeftBtn();
			}
		}
	}
	
	public void onRightBtn(View v) {
		ShakeTabEvent e = (ShakeTabEvent)this.getCurrentActivity();
		if (e != null) {
			e.onRightBtn();
		}
	}
	
	public int getTabPanelHeight() {
		View v = findViewById(R.id.shake_tab_group);
		if (v != null) {
			return v.getMeasuredHeight();
		}
		return 0;
	}
	
	protected void onStart() {
		super.onStart();
		showUnreadCount();
		MessageFetcher.getShared().addListener(this);
	}
	protected void onStop() {
		super.onStop();
		MessageFetcher.getShared().removeListener(this);	
	}

	private void showUnreadCount() {
		if (DataManager.getShared() == null) {
			return;
		}
		
		int unreadCount = DataManager.getShared().getTotalUnreadMsgCount();
		if (unreadCount > 0) {
			if (txtUnreadMsgFlag != null) {
				if (unreadCount >= 100) {
					txtUnreadMsgFlag.setText("N");
				}
				else {
					txtUnreadMsgFlag.setText(String.valueOf(unreadCount));
				}
				txtUnreadMsgFlag.setVisibility(View.VISIBLE);
			}
		}
		else {
			txtUnreadMsgFlag.setVisibility(View.GONE);
		}
	}
	
	public void onNewMessageArrived() {
		// TODO Auto-generated method stub
		showUnreadCount();
	}
}
